/**
 * @(#) HttpClientUtils.java
 *
 * @author lihg
 * @version V1.0 2013-10-1
 *
 * Copyright (C) 2010,2013 , Lihg
 */

/**
 * 
 */
package cn.com.dshome.acquisition.utils;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import cn.com.dshome.acquisition.exception.AcquisitionException;

/**
 * 
 * Purpose:HttpClientUtils
 * 
 * @author lihg
 * @see
 * @since
 */
@Service
public class HttpClientUtils implements Serializable {

	private static final long serialVersionUID = 663052679545702869L;

	private Pattern charsetPattern = Pattern.compile(".*?=(.*)") ;

	private String chartSet  ;

	//响应内容
	public static final String RESPONSE_MESSAGE  = "message" ;

	//消息头
	public static final String RESPONSE_HEADERS = "headers" ;

	/**
	 * 返回响应信息
	 * @param uri  请求路径
	 * @param parameters 参数
	 * @return
	 * @throws AcquisitionException
	 */
	public byte[] getResponseMessage(final String uri,	final NameValuePair... parameters) throws AcquisitionException {
		return (byte[])simulateOperation(uri,parameters).get(RESPONSE_MESSAGE) ;
	}

	/**
	 * 返回响应头信息
	 * @param uri
	 * @param parameters
	 * @return
	 * @throws AcquisitionException
	 */
	public Header[] simulateLogin(String uri,NameValuePair... parameters) throws AcquisitionException{
		return (Header[])simulateOperation(uri,parameters).get(RESPONSE_HEADERS) ;
	}

	/**
	 * 模拟操作
	 * @param uri
	 * @param parameters
	 * @return
	 * @throws AcquisitionException
	 */
	public Map<String,Object> simulateOperation(String uri,NameValuePair... parameters) throws AcquisitionException{
		if (null == uri || uri.equalsIgnoreCase("")) {
			throw new AcquisitionException("uri can't be null ! please check it !");
		} else {
			// 创建HttpClient
			HttpClient httpClient = null ;
			try {
				httpClient = new DefaultHttpClient();
				setTimeOut(httpClient) ;
				// 创建HttpPost
				final HttpPost httpPost = new HttpPost(uri);
				if (null != parameters && parameters.length > 0) {
					final UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(Arrays.asList(parameters), "utf-8");
					httpPost.setEntity(uefEntity);
				}
				HttpResponse response = httpClient.execute(httpPost);
				Integer statusCode = response.getStatusLine().getStatusCode();
				HttpEntity entity = null;
				if (statusCode != 200) {//Post请求不支持则用Get
					httpClient.getConnectionManager().shutdown();
					httpClient = new DefaultHttpClient();
					setTimeOut(httpClient) ;
					HttpGet httpGet = new HttpGet(uri);
					response = httpClient.execute(httpGet);
					entity = response.getEntity();
					setChartSet(getChartSet(entity.getContentType().getValue(),"get")) ;
				} else {
					entity = response.getEntity();
					setChartSet(getChartSet(entity.getContentType().getValue(),"post")) ;
				}
				//转换为Byte数组
				byte[] responseMessage = EntityUtils.toByteArray(entity)  ;
				//返回响应信息
				Map<String,Object> responseMap = new HashMap<String,Object>() ;
				//设置响应信息
				responseMap.put(RESPONSE_MESSAGE,responseMessage) ;
				//设置Headers
				responseMap.put(RESPONSE_HEADERS,response.getAllHeaders()) ;
				return responseMap ;
			} catch (final ClientProtocolException e) {
				throw new AcquisitionException(e);
			} catch (final UnsupportedEncodingException e) {
				throw new AcquisitionException(e);
			} catch (final IOException e) {
				throw new AcquisitionException(e);
			} finally {
				httpClient.getConnectionManager().shutdown();
			}
		}
	}

	/**
	 * 获取字符编码
	 * @param contentType
	 * @return
	 */
	private String getChartSet(String contentType,String method){
		Matcher charsetMatcher = charsetPattern.matcher(contentType) ;
		if(charsetMatcher.find()){
			return charsetMatcher.group(1) ;
		}else if("post".equalsIgnoreCase(method)){
			return "utf-8" ;
		}else{
			return "gb2312" ;
		}
	}

	/**
	 * 设置超时时间
	 * @param client
	 */
	private void setTimeOut(HttpClient client){
		if(null != client){
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,300000) ;//连接时间
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT , 1500000) ;//数据传输超时时间
		}
	}


	/**
	 * @return the chartSet
	 */
	public String getChartSet() {
		return chartSet;
	}


	/**
	 * @param chartSet the chartSet to set
	 */
	private void setChartSet(String chartSet) {
		this.chartSet = chartSet;
	}

}

/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2013-10-1 下午05:51:51 lihg 创建版本
 */
